//
//  YDKeyboardViewController.m
//  IngCard
//
//  Created by kf on 2017/6/8.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDTextViewKeyboardViewController.h"

static CGFloat const kToolbarHeight = 50;
static CGFloat const kContainerViewHeight = 300;

@interface YDTextViewKeyboardViewController ()<QMUIKeyboardManagerDelegate>
@property(nonatomic, strong) QMUIKeyboardManager *keyboardManager;

@property(nonatomic, strong) UIControl *maskControl;

@property(nonatomic, strong) UIView *toolbarView;
@property(nonatomic, strong) QMUIButton *cancelButton;
@property(nonatomic, strong) QMUIButton *publishButton;

@property(nonatomic, strong) UIView *containerView;
@property(nonatomic, strong) QMUITextView *textView;
@property(nonatomic, strong) UIImageView *editingImageView;
@property(nonatomic, strong) UIImageView *contentBackground;

@property(nonatomic, copy) void (^onComplete)(NSString *);
@property(nonatomic, copy) void (^onCancel)(void);
@property(nonatomic, assign) BOOL beCancel;
@end

@implementation YDTextViewKeyboardViewController

- (void)initSubviews {
    [super initSubviews];
    
    [self.keyboardManager addTargetResponder:self.textView];
    
    self.view.backgroundColor = UIColorClear;
    
    self.maskControl.frame = self.view.bounds;
    [self.view addSubview:self.maskControl];
    
    self.containerView.frame = CGRectFlatMake(0, CGRectGetHeight(self.view.bounds),
                                              CGRectGetWidth(self.view.bounds), kContainerViewHeight);
    [self.view addSubview:self.containerView];
    
    [self initContainerView];
    self.toolbarView.frame = CGRectFlatMake(0, CGRectGetHeight(self.containerView.bounds) - kToolbarHeight,
                                            CGRectGetWidth(self.containerView.bounds), kToolbarHeight);
    [self.containerView addSubview:self.toolbarView];
    

    [self.containerView addSubview:self.textView];
    
    self.cancelButton.frame = CGRectFlatMake(20,
                                             CGFloatGetCenter(CGRectGetHeight(self.toolbarView.bounds), CGRectGetHeight(self.cancelButton.bounds)),
                                             CGRectGetWidth(self.cancelButton.bounds),
                                             CGRectGetHeight(self.cancelButton.bounds));
    [self.toolbarView addSubview:self.cancelButton];

    self.publishButton.frame = CGRectFlatMake(CGRectGetWidth(self.toolbarView.bounds) - CGRectGetWidth(self.publishButton.bounds) - 20,
                                              CGFloatGetCenter(CGRectGetHeight(self.toolbarView.bounds), CGRectGetHeight(self.publishButton.bounds)),
                                              CGRectGetWidth(self.publishButton.bounds),
                                              CGRectGetHeight(self.publishButton.bounds));

    [self.toolbarView addSubview:self.publishButton];
}

-(void)initContainerView
{
    [self.containerView addSubview:self.editingImageView];
    [self.editingImageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(27);
        make.top.equalTo(0);
        make.width.equalTo(10);
        make.height.equalTo(10);
    }];
    
    [self.containerView addSubview:self.contentBackground];
    [self.contentBackground makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(25);
        make.right.equalTo(-20);
        make.top.equalTo(0);
        make.height.equalTo(kContainerViewHeight - kToolbarHeight - 50);
    }];
    
    [self.containerView addSubview:self.textView];
    [self.textView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(33);
        make.right.equalTo(-36);
        make.top.equalTo(self.contentBackground).offset(10);
        make.bottom.equalTo(self.contentBackground).offset(-10);
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

#pragma mark - public
- (BOOL)isShowing
{
    if (self.parendViewController &&
        self.view.superview)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)showWithPlaceholder:(NSString *)placeholder
                 onComplete:(void (^)(NSString *)) onComplete
                   onCancel:(void (^)())onCancel
{
    if (self.parendViewController && ![self isShowing])
    {
        self.view.frame = self.parendViewController.view.bounds;
        [self.parendViewController.view addSubview:self.view];
        [self.view layoutIfNeeded];
        
        
        self.maskControl.alpha = 0.0;
        [UIView animateWithDuration:0.25 delay:0.0 options:QMUIViewAnimationOptionsCurveOut animations:^{
            self.maskControl.alpha = 1.0;
        }completion:^(BOOL finished){}];
        
        self.textView.text = placeholder;
        [self.textView becomeFirstResponder];
        
        self.onComplete = onComplete;
        self.onCancel = onCancel;
        self.beCancel = NO;
    }
}

- (void)hide
{
    __weak __typeof(self)weakSelf = self;
    
    [self.textView resignFirstResponder];
    !self.beCancel ? self.onComplete(self.textView.text) : self.onCancel();
    
    self.onCancel = nil;
    self.onComplete = nil;
    self.textView.text = nil;
    self.textView.placeholder = @"添加描述...";
    
    
    [UIView animateWithDuration:.25 delay:0.0 options:QMUIViewAnimationOptionsCurveOut animations:^
    {
        __strong __typeof(weakSelf)self = weakSelf;
        self.maskControl.alpha = 0.0;
    } completion:^(BOOL finished)
    {
        __strong __typeof(weakSelf)self = weakSelf;
        [self.view removeFromSuperview];
    }];
}

#pragma mark - <QMUIKeyboardManagerDelegate,UITextFieldDelegate>

- (void)keyboardWillChangeFrameWithUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo {
    __weak __typeof(self)weakSelf = self;
    [QMUIKeyboardManager handleKeyboardNotificationWithUserInfo:keyboardUserInfo
                                                      showBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo)
     {
         
         [QMUIKeyboardManager animateWithAnimated:NO
                                 keyboardUserInfo:keyboardUserInfo
                                       animations:^
          {
              __strong __typeof(weakSelf)self = weakSelf;
              CGFloat distanceFromBottom = [QMUIKeyboardManager distanceFromMinYToBottomInView:weakSelf.view
                                                                                  keyboardRect:keyboardUserInfo.endFrame];
              
              CGFloat pointY = CGRectGetHeight(self.view.bounds) - distanceFromBottom - kContainerViewHeight;
              self.containerView.frame = CGRectMake(0, pointY, CGRectGetWidth(self.view.bounds), kContainerViewHeight);
          } completion:NULL];
     } hideBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo)
     {
         __strong __typeof(weakSelf)self = weakSelf;
         [self hide];
         self.containerView.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds),
                                               CGRectGetWidth(self.view.bounds), kContainerViewHeight);
         
     }];
}

#pragma mark - private
- (void)handleCompleteButtonEvent:(id)sender
{
    [self.textView resignFirstResponder];
}

- (void)handleCancelButtonEvent:(id)sender
{
    self.beCancel = YES;
    [self.textView resignFirstResponder];
}

#pragma mark - lazy load
-(UIControl *)maskControl
{
    if (!_maskControl)
    {
        _maskControl = [[UIControl alloc] init];
        _maskControl.backgroundColor = UIColorMask;
        [_maskControl addTarget:self action:@selector(handleCancelButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _maskControl;
}

-(UIView *)containerView
{
    if (!_containerView)
    {
        _containerView = [[UIView alloc] init];
        _containerView.backgroundColor = UIColorClear;
    }
    return _containerView;
}

-(QMUITextView *)textView
{
    if (!_textView)
    {
        _textView = [[QMUITextView alloc] init];
        _textView.font = UIFontMake(14);
        _textView.textContainerInset = UIEdgeInsetsMake(26, 12, 26, 12);
        _textView.placeholder = @"请输入...";
        [_textView setBackgroundColor:UIColorClear];
    }
    return _textView;
}

-(UIView *)toolbarView
{
    if (!_toolbarView)
    {
        _toolbarView = [[UIView alloc] init];
        _toolbarView.backgroundColor = UIColorForBackground;
        _toolbarView.qmui_borderColor = UIColorSeparator;
        _toolbarView.qmui_borderPosition = QMUIBorderViewPositionTop;
    }
    return _toolbarView;
}

-(QMUIButton *)cancelButton
{
    if (!_cancelButton)
    {
        _cancelButton = [[QMUIButton alloc] init];
        _cancelButton.titleLabel.font = UIFontMake(16);
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(handleCancelButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_cancelButton sizeToFit];
    }
    return _cancelButton;
}

-(QMUIButton *)publishButton
{
    if (!_publishButton)
    {
        _publishButton = [[QMUIButton alloc] init];
        _publishButton.titleLabel.font = UIFontMake(16);
        [_publishButton setTitle:@"确认" forState:UIControlStateNormal];
        [_publishButton addTarget:self action:@selector(handleCompleteButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_publishButton sizeToFit];
    }
    return _publishButton;
}

-(QMUIKeyboardManager *)keyboardManager
{
    if (!_keyboardManager)
    {
        _keyboardManager = [[QMUIKeyboardManager alloc] initWithDelegate:self];
    }
    return _keyboardManager;
}



-(UIImageView *) contentBackground
{
    if (!_contentBackground)
    {
        _contentBackground = [UIImageView new];
        UIImage *image = UIImageMake(@"contact_content_background");
        image = [image  stretchableImageWithLeftCapWidth:image.size.width*0.3 topCapHeight:image.size.height*0.7];
        _contentBackground.image = image;
        _contentBackground.contentMode = UIViewContentModeScaleToFill;
    }
    return _contentBackground;
}


-(UIImageView *) editingImageView
{
    if (!_editingImageView)
    {
        _editingImageView = [UIImageView new];
        _editingImageView.image = UIImageMake(@"contact_detail_editing");
        _editingImageView.contentMode = NSTextAlignmentLeft;
        [_editingImageView sizeToFit];
    }
    return _editingImageView;
}

@end
